const {EOL} = require('os')
const jwt = require('jsonwebtoken')
const moment = require('moment');
const fs = require('fs')

// 记录日志
function writeLog(req, res, next) {
    let time = moment().format('YYYY-MM-DD HH:mm:ss')
    let ip = req.ip
    let method = req.method
    let uri = req.url
    let status = 'ok'
    let content = time + ' ' + ip + ' ' + method + ' ' + uri + ' ' + status
    if(fs.existsSync('./logs/api.log')) {
        let log = fs.readFileSync('./logs/api.log', 'utf-8')
        if(log) {
            fs.appendFile('./logs/api.log',EOL+content, () => {})
        } else {
            fs.writeFile('./logs/api.log', content, () => {})
        }
    } else {
        fs.writeFile('./logs/api.log', content, () => {})
    }
    next()
}

// 验证令牌
function checkToken(req,res,next){
    let responseObj = {
        errorCode:0,
        msg:'成功'
    }
    let token = req.headers.authorization
    if(!token){
        responseObj.errorCode = 401,
        responseObj.msg = '令牌缺失'
        res.json(responseObj)
        return
    }else{
        let decodeObj 
        try{

            decodeObj = jwt.verify(token,'asdsdf')

            if(decodeObj.startTime+decodeObj.expires <= +new Date()){
                responseObj.errorCode=405,
                responseObj.msg = '令牌过期'
                res.json(responseObj)
                return
            }else{
                next()
            }
        }catch(err){
            responseObj.errorCode=402,
            responseObj.msg = '令牌缺失'
            res.json(responseObj)
            return
        }
    }
}
module.exports ={
    writeLog,checkToken
}